package com.cswnode.demo.controller;

import com.cswnode.demo.entity.Page;
import com.cswnode.demo.entity.Student;
import com.cswnode.demo.service.StudentService;
import com.cswnode.demo.util.ResponseVo;
import com.cswnode.demo.vo.StuQuery;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学生信息表(Student)表控制层
 *
 * @author makejava
 * @since 2021-03-20 15:51:03
 */
@Api(tags = "学生管理模块")
@RestController
@RequestMapping("/student")
public class StudentController {
    /**
     * 服务对象
     */
    @Autowired
    private StudentService studentService;



    @ApiOperation(value = "添加学生")
    @PostMapping("/add")
    public ResponseVo add(@RequestBody Student student){
        if (student == null){
            return ResponseVo.error("学生信息不能为空！");
        }
        String insert = studentService.insert(student);
        if (insert == null){
            return ResponseVo.success("添加成功！");
        }
        return ResponseVo.error(insert);
    }

    @ApiOperation(value = "查询学生")
    @PostMapping("/get")
    public ResponseVo get(){
        Student student =  studentService.getStudent();
        return ResponseVo.success(student);
    }

    @ApiOperation(value = "分页查询学生")
    @PostMapping("/query")
    public ResponseVo query(@RequestBody StuQuery stuQuery){
        Map<String,Object> result = new HashMap<>();
        Page page = new Page();
        page.setCurrent(stuQuery.getCurrent());
        page.setLimit(stuQuery.getLimit());
        page.setRows(studentService.selectNum(stuQuery));
        List<Student> students = studentService.queryAllByLimit(page.getOffset(), page.getLimit(), stuQuery);
        result.put("page",page);
        result.put("students",students);
        return ResponseVo.success(result);
    }


    @ApiOperation(value = "修改学生")
    @PostMapping("/update")
    public ResponseVo update(@RequestBody Student student){
        if (ObjectUtils.isEmpty(student)){
            return ResponseVo.error("学生信息不得为空！");
        }
        String update = studentService.update(student);
        if (update == null){
            return ResponseVo.success("修改成功！");
        }
        return ResponseVo.error(update);
    }

    @ApiOperation(value = "删除学生")
    @GetMapping("/delete/{stuId}")
    public ResponseVo delete (@PathVariable("stuId")Long stuId){
        if (stuId == null){
            return ResponseVo.error("删除失败！");
        }
        boolean result = studentService.deleteById(stuId);
        if (!result){
            return ResponseVo.error("删除失败");
        }
        return ResponseVo.success("删除成功");
    }

}